/******************************************************树形*****************************************************/

var onTreeClick = function(event, treeId, treeNode) {
    var $div = $(event.target).closest("div.ui-Tree");
    var objId = $div.attr("formId");
    var obj = _$.getById(objId);
    if(treeNode){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        var idField = obj.getOption("idField");
        var multiple = obj.getOption("multiple");
        if(!multiple) {
            var value = treeNode[idField];
            obj.setValue(value);
        }
    }
};
var onTreeCheck = function(event, treeId, treeNode) {
    var $div = $(event.target).closest("div.ui-Tree");
    var objId = $div.attr("formId");
    var obj = _$.getById(objId);

    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    var nodes = treeObj.getCheckedNodes(true);
    var idField = obj.getOption("idField");

    if(nodes != null && nodes.length >0){
        var values = [];
       for(var i=0;i<nodes.length;i++){
           var node = nodes[i];
           var value = node[idField];
           values.add(value)
       }
        obj.setValue(values.join(","));
    }else{
        obj.setValue("");
    }
};

_$.Tree=function (target){
    var _this = this;
    _$.Tree.superclass.constructor.call(_this,target);
};
_$.regClass("Tree",_$.Tree);

_$.extend(_$.Tree,_$.FormItem, {
    _cls:_$._clsPre + "Tree",
    _uiCls:_$._uiPreCls + "Tree",
    _attrProps:function(){
        var _this = this;
        var properties = _$.Tree.superclass._attrProps.call(_this);
        properties.addAll(["onchange","basePath","cascadeYes","cascadeNo","apiServer","call","idField","textField",'parentId','parentKey',"resultKey",{"multiple":"boolean","params":"object"}]);
        return properties;
    },
    _attrOpts:function(){
        var _this = this;
        var opts = _$.Tree.superclass._attrOpts.call(_this);
        return $.extend(true,opts,{
            "basePath":"/base",
            "apiServer":"base",
            "idField":"id",
            "textField":"name",
            "multiple":false,
            "parentKey":"parentId",
            "resultKey":"nodes",
            "cascadeYes":"",
            "cascadeNo":""
        });
    },
    _editModel:function(){
        var _this = this;
        _this._clearShow();
        var source='<ul id="tree_'+_this.id+'" class="ztree"></ul>';
        _this._replaceNode(source);
        _this.component = $(".ztree",_this.el);
        _this.initTree();
        _this.el.addClass(_this._uiCls);
        _this._setStyle();
        _this.setOption("model",_EDITABLE_);
        _this._init();
        _this._bindEvents();
    },
    initTree:function(){
        var _this = this;
        _this._loadData(null,_this._editInit);
    },
    _init:function(){
        var _this = this;
        if(!_this._isEdit()){
            _this._initShow();
        }
    },
    _initShow:function(value){
        var _this = this;
        _this._loadData(value,_this._showInit);
    },
    _loadData:function(value,func){
        var _this = this;
        var parentKey = _this.getOption("parentKey");
        var apiServer = _this.getOption("apiServer");
        var call = _this.getOption("call");
        var idField = _this.getOption("idField");
        var basePath = _this.getOption("basePath");
        var params = _this.getOption("params");
        if(params == null){
            params = {};
        }
        _this.data = [];
        if(isNotEmpty(value)){
            params[idField] = value;

        }
        var route = {
            "apiServer":apiServer,
            "call":call,
            "description":"查询树形数据"
        };

        var url= basePath + "/callService";
        var options = {
            url:url,
            route:route,
            data:params,
            callback:function(result){
                func.call(_this,result);
            }
        } ;
        $.cc.ajaxDtoRequestCommon(options);
    },

    _editInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        if(state == 0){
            var resultKey = _this.getOption("resultKey");
            var nodes = result.get(resultKey);
            _this.data=nodes;

            var idField = _this.getOption("idField");
            var textField = _this.getOption("textField");
            var parentKey = _this.getOption("parentKey");
            var multiple = _this.getOption("multiple");
            var cascadeYes = _this.getOption("cascadeYes");
            var cascadeNo = _this.getOption("cascadeNo");

            if(!multiple){
                var setting = {
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: idField,
                            pIdKey:parentKey
                        }
                    },
                    callback: {
                        onClick: onTreeClick
                    },
                    view: {
                        showLine:false
                    }
                };
            }else{
                var setting = {
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: idField,
                            pIdKey: parentKey,
                            name:textField
                        }
                    },
                    callback: {
                        onCheck: onTreeCheck
                    },
                    check: {
                        enable: true,
                        chkboxType: { "Y": cascadeYes, "N": cascadeNo }
                    },
                    view: {
                        showLine:false
                    }
                };
            }

            $.fn.zTree.init($("#tree_" + _this.id), setting, nodes);

            var initValue= _this.options["initValue"];
            if(isNotEmpty(_this.value)){
                _this.setValue(_this.value);
            }else if(isNotEmpty(initValue)){
                _this.setValue(initValue);
            }
        }else{
            $.cc.error(info);
        }
        _this._loadSuccess();
    },
    _showInit:function(result){
        var _this = this;
        var state = result.getState();
        var info = result.getInfo();
        var resultKey = _this.getOption("resultKey");
        if(state == 0){
            var nodes = result.get(resultKey);
            _this.data = nodes;
            var initValue = _this.getOption("initValue");
            if(isNotEmpty(_this.value)){
                _this.setValue(_this.value);
            }else if (isNotEmpty(initValue)){
                _this.setValue(initValue);
            }
        }else{
            $.cc.error(info);
        }
        _this._loadSuccess();
    },
    _bindEvents:function(){
        var _this = this;
        _$.Tree.superclass._getEvents.call(_this, ["onfocus","oninput","onblur","onchange"]);
        if(_this._isEdit()){
        }
    },
    _setStyle:function(){

    },

    setValue:function(value,change) {
        var _this = this;
        _this.value = value;
        if(isEmpty(change)){
            change = true;
        }

        var idField = _this.getOption("idField");
        var textField = _this.getOption("textField");
        var multiple = _this.getOption("multiple");
        var treeId = "tree_" + _this.id;
        var treeObj = $.fn.zTree.getZTreeObj(treeId);

        if(isEmpty(value) || isEmpty(_this.data) || _this.data.length == 0){
            _this.value = null;
        }else{
            _this.value = value;
            if (_this._isEdit()) {
                if(!multiple){
                    var nodes = treeObj.getNodesByParam(idField,value, null);
                    if(nodes != null && nodes.length>0){
                        var node = nodes[0];
                        if(node  != null){
                            treeObj.selectNode(node);
                        }
                    }
                }else{
                    treeObj.checkAllNodes(false);
                    var values = (value+"").split(",");
                    if(values != null && values.length>0){
                        for(var i=0;i<values.length;i++){
                            var val = values[i];
                            var nodes = treeObj.getNodesByParam(idField,val, null);
                            if(nodes != null && nodes.length>0){
                                var node = nodes[0];
                                if(node  != null){
                                    treeObj.checkNode(node, true, false);
                                }
                            }
                        }
                    }
                }

            } else {
                if(!multiple){
                     var flag = _this.data.some(function(item,i){
                        var id = item[idField];
                        var name = item[textField];

                        if(id == value){
                            _this.component.html(name);
                            return true;
                        }
                        return false;
                    });

                    if(!flag){
                        _this.value = null;
                        _this.component.html("");
                    }

                }else{
                    var values = (value+"").split(",");
                    if(values != null && values.length>0){
                        var names=[] ;
                        for(var i=0;i<values.length;i++){
                            var itemValue = values[i];

                            _this.data.each(function(item,i){
                                var id = item[idField];
                                var name = item[textField];
                                if(id == itemValue){
                                    names.add(name);
                                }
                            });
                        }
                        if(names.length>0){
                            _this.component.html(names.join(","));
                        }else{
                            _this.value = null;
                            _this.component.html('');
                        }
                    }else{
                        _this.value = null;
                        _this.component.html(names.join(","));
                    }

                }
            }
        }
        if(change){
            _this._fire("onchange");
        }
    },
    getValue:function(){
        var _this = this;
        return _this.value;
    }
});
